<?php

namespace App\Http\Controllers\Api;


use App\Models\Task;
use App\Models\TaskLog;
use App\Models\User;
use App\Services\TaskService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;

/***
 * 任务中心
 * Class TaskController
 * @package App\Http\Controllers\Api
 */
class TaskController extends Controller
{
    public function index()
    {
        $type = request()->input('type', false);
        $list = Task::where(function ($query) use ($type) {
            if ($type) {
                $query->where('type_id', $type);
            }
        })
            ->where('status', 1)
            ->orderBy('created_at', 'DESC')
            ->paginate(100);
        $data = [];
        $surplus = 0;
        $start_time = Carbon::now()->startOfDay()->toDateTimeString();
        $end_time = Carbon::now()->endOfDay()->toDateTimeString();
        foreach($list as &$value){
            $value['type_str'] = Task::TYPE[$value['type_id']];
            $value['num'] = 0;
            if ($value['type_id'] == 'new') {//新手任务
                $task_log = TaskLog::where(['user_id' => $this->user->id, 'task_id' => $value['id']])->first();
                if (!empty($task_log)) {
                    $value['status'] = 1;//领取任务
                    $value['lingqu'] = $task_log['status'];
                    if ($value['lingqu'] == 0) {//未发放奖励
                        array_push($data, $value->toArray());
                    }
                } else {
                    $value['status'] = 0;//未领取任务
                    $value['lingqu'] = 0;
                    array_push($data, $value->toArray());
                }
            } elseif ($value['type_id'] == 'day') {//每日任务

                $task_log = TaskLog::where(['user_id' => $this->user->id, 'task_id' => $value['id']])->whereBetween('created_at', [$start_time, $end_time])->get();
                $value['num'] = count($task_log);//完成次数
                if ($value['num'] >= $value['require']) {//任务完成
                    $value['lingqu'] = $task_log[0]['status'];
                    if ($value['lingqu'] == 0) {
                        array_push($data, $value->toArray());
                    }
                } else {//未完成任务
                    $value['lingqu'] = 0;
                    $value['status'] = 0;
                    array_push($data, $value->toArray());
                }
            }
            if (!$value['status']) {
                $surplus += $value['price'];
            }
        }
        $datalist['list'] = $data;
        $datalist['surplus'] = $surplus;
        $datalist['dayprice'] = TaskLog::where('user_id', $this->user->id)->where('status', 1)->whereBetween('created_at', [$start_time, $end_time])->sum('amount');
        return $this->success('成功', $datalist);
    }

    public function store(Request $request)
    {
        if (empty($request->type)) {
            return $this->error('请选择分类');
        }
        if (empty($request->name)) {
            return $this->error('请选择任务');
        }
        if (empty($request->title)) {
            return $this->error('请填写任务名');
        }
        if (empty($request->need_num)) {
            return $this->error('请填写任务完成需求量');
        }
        if (empty($request->integral)) {
            return $this->error('请填写任务完成获得积分');
        }
        $model = new Task();
        $model->user_id = $this->getUserId();
        $request->type AND $model->type = $request->type;
        $request->name AND $model->name = $request->name;
        $request->title AND $model->title = $request->title;
        $request->need_num AND $model->need_num = $request->need_num;
        $request->integral AND $model->integral = $request->integral;
        $request->sort AND $model->sort = $request->sort;
        $model->status = 1;
        $result = $model->save();
        if ($result) {
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败');
        }
    }

    public function update(Request $request, $id)
    {
        if (empty($request->type)) {
            return $this->error('请选择分类');
        }
        if (empty($request->name)) {
            return $this->error('请选择任务');
        }
        if (empty($request->title)) {
            return $this->error('请填写任务名');
        }
        if (empty($request->need_num)) {
            return $this->error('请填写任务完成需求量');
        }
        if (empty($request->integral)) {
            return $this->error('请填写任务完成获得积分');
        }
        $model = Task::find($id);
        $model->user_id = $this->getUserId();
        $request->type AND $model->type = $request->type;
        $request->name AND $model->name = $request->name;
        $request->title AND $model->title = $request->title;
        $request->need_num AND $model->need_num = $request->need_num;
        $request->integral AND $model->integral = $request->integral;
        $request->sort AND $model->sort = $request->sort;
        $model->status = 1;
        $result = $model->save();
        if ($result) {
            return $this->success('修改成功', $result);
        } else {
            return $this->error('修改失败');
        }
    }

    public function destroy($id)
    {
        $result = Task::where('id', $id)->update(['status' => 0]);
        if ($result) {
            return $this->success('禁用成功', $result);
        } else {
            return $this->error('禁用失败');
        }
    }

    public function batchDisable(Request $request)
    {
        $input = $request->toArray();
        if (!in_array($input['status'], [0, 1])) {
            return $this->error('状态不正确');
        }
        $result = Task::whereIn('id', $input['selection'])->update(['status' => $input['status']]);
        if ($result) {
            return $this->success('保存成功');
        } else {
            return $this->error('保存失败');
        }
    }

    public function getInit(Request $request)
    {
        return $this->success('获取成功', [
            'TASK_TYPE' => TaskService::$TASK_TYPE,
            'DAILY_TASK' => TaskService::$DAILY_TASK,
        ]);
    }

    /***
     * 发放任务奖励
     * @param Request $request
     */
    public function grantTask(Request $request, Task $task)
    {
        if (!$request->has('task_id') && !is_numeric($request->task_id)) {
            return $this->error('任务id错误');
        }
        $taskinfo = $task::where('id', $request->task_id)->first();
        if (empty($taskinfo)) {
            return $this->error('任务不存在');
        }
        if ($taskinfo['type_id'] == 'new') {//新手任务
            $task_log = TaskLog::where(['user_id' => $this->user->id, 'task_id' => $taskinfo['id']])->first();
            if (empty($task_log)) {
                return $this->error('该任务未达标，暂不能领取爽豆');
            }
            if ($task_log['status'] == 1) {
                return $this->error('该任务已经领取');
            } else {
                //修改任务记录状态
                $task_log->status = 1;
                $task_log->save();
                //用户到账
                User::integral($this->user->id, $taskinfo['price'], '新手任务奖励', 'TASK-' . $taskinfo['id']);
                //变动记录
                return $this->success('领取成功');
            }
        } elseif ($taskinfo['type_id'] == 'day') {//每日任务
            $start_time = Carbon::now()->startOfDay()->toDateTimeString();
            $end_time = Carbon::now()->endOfDay()->toDateTimeString();
            $task_log = TaskLog::where(['user_id' => $this->user->id, 'task_id' => $taskinfo['id']])->whereBetween('created_at', [$start_time, $end_time])->get();
            if ($task_log->isEmpty()) {
                return $this->error('该任务未达标，暂不能领取爽豆');
            }
            $task_num = count($task_log);//完成次数
            if ($task_num < $taskinfo['require']) {
                return $this->error('该任务未达标，暂不能领取爽豆');
            } else {
                TaskLog::where(['user_id' => $this->user->id, 'task_id' => $taskinfo['id']])->whereBetween('created_at', [$start_time, $end_time])->update(['status' => 1]);
                User::integral($this->user->id, $taskinfo['price'], '每日任务奖励', 'TASK-' . $taskinfo['id']);
                return $this->success('领取成功');
            }
        }
    }
}
